//生产环境的插件
import type { Plugin } from 'vite'
import { mkdirSync, readFileSync, writeFileSync } from 'fs'
import * as builder from 'electron-builder'
import path from 'path'

const buildFrame = () => {
  require('esbuild').buildSync({
    entryPoints: ['src/frame.ts'],
    bundle: true,
    outfile: 'dist/frame.js',
    platform: 'node',
    target: 'node12',
    format: 'cjs',
    external: ['electron']
  })
}

export const ElectronProdPlugin = (): Plugin => {
  return {
    name: 'electron-prod',
    closeBundle() {
      buildFrame()
      //electron-builder 指定package.json中的main字段为dist/frame.js
      const json = JSON.parse(readFileSync('package.json', 'utf-8'))
      json.main = 'frame.js'
      writeFileSync('dist/package.json', JSON.stringify(json, null, 2))
      //避免electron-builder打包时下载node_modules
      mkdirSync('dist/node_modules')
      builder.build({
        config: {
          directories: {
            output: path.resolve(process.cwd(), 'release'),
            app: path.resolve(process.cwd(), 'dist')
          },
          asar: true,
          appId: 'fun.zzzz.vueapp',
          productName: 'vue-electron',
          nsis:{
            oneClick: false,// 是否一键安装
            allowToChangeInstallationDirectory: true,// 是否允许修改安装目录
          }
        }
      })
    }
  }
}
